import { DirectiveOptions } from 'vue';
import { VNode } from 'vue/types/umd';
import { DirectiveBinding } from 'vue/types/options';

export const ClickOutside: DirectiveOptions = {
  bind(el: HTMLElement, binding: DirectiveBinding, vnode: VNode) {
    function documentHandler(e: any) {
      if (el.contains(e.target)) {
        return false;
      }
      if (binding.expression) {
        binding.value(e);
      }
    }
    (el as any).__vueClickOutside__ = documentHandler;
    document.addEventListener('click', documentHandler);
  },

  unbind(el: HTMLElement, binding: DirectiveBinding) {
    document.removeEventListener('click', (el as any).__vueClickOutside__);
    delete (el as any).__vueClickOutside__;
  }
};